/**
 * 写作Agent - IntelliMark适配版
 * 专门为Markdown文档写作设计的AI代理
 */

import { HumanMessage, SystemMessage } from "@langchain/core/messages";
import { AgentConfig, AgentResult, WritingContext, WritingTaskType } from "../types/agent";
import { getEnhancedAIProviderManager } from "../utils/aiProviderAdapter";
import { getPromptTemplateManager } from "../utils/promptTemplates";
import { v4 as uuidv4 } from 'uuid';

// 写作Agent配置
export interface WritingAgentConfig {
  specialties: WritingTaskType[];
  defaultStyle: 'formal' | 'casual' | 'academic' | 'creative' | 'technical';
  autoContext: boolean;
  learningEnabled: boolean;
  collaborationMode: boolean;
  memoryEnabled: boolean;
}

// 写作任务
export interface WritingTask {
  id: string;
  type: WritingTaskType;
  input: string;
  context?: WritingContext;
  options?: Record<string, any>;
  priority: number;
  createdAt: Date;
}

export class WritingAgent {
  private config: WritingAgentConfig;
  private taskQueue: WritingTask[] = [];
  private isProcessing = false;
  private memory: Map<string, any> = new Map();

  constructor(config: Partial<WritingAgentConfig> = {}) {
    this.config = {
      specialties: ['generate', 'polish', 'expand', 'continue', 'summarize'],
      defaultStyle: 'creative',
      autoContext: true,
      learningEnabled: true,
      collaborationMode: false,
      memoryEnabled: true,
      ...config,
    };
  }

  // 主要写作方法
  async processTask(task: WritingTask): Promise<AgentResult> {
    const startTime = Date.now();
    const taskId = task.id || uuidv4();

    try {
      // 检查任务类型是否支持
      if (!this.config.specialties.includes(task.type)) {
        throw new Error(`Task type ${task.type} not supported by this agent`);
      }

      // 获取上下文
      const context = await this.getContext(task);

      // 构建消息
      const messages = await this.buildMessages(task, context);

      // 执行任务
      const response = await this.executeTask(messages, task);

      // 学习和记忆
      if (this.config.learningEnabled) {
        await this.learnFromTask(task, response);
      }

      if (this.config.memoryEnabled) {
        await this.storeMemory(task, response);
      }

      const executionTime = Date.now() - startTime;

      return {
        success: true,
        result: response.content,
        metadata: {
          taskId,
          taskType: task.type,
          executionTime,
          contextUsed: !!context,
          style: this.config.defaultStyle,
        },
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);

      return {
        success: false,
        error: errorMessage,
        metadata: {
          taskId,
          taskType: task.type,
          executionTime: Date.now() - startTime,
        },
      };
    }
  }

  // 快速写作方法
  async write(
    prompt: string,
    type: WritingTaskType = 'generate',
    options?: Record<string, any>
  ): Promise<string> {
    const task: WritingTask = {
      id: uuidv4(),
      type,
      input: prompt,
      options,
      priority: 1,
      createdAt: new Date(),
    };

    const result = await this.processTask(task);

    if (!result.success) {
      throw new Error(result.error || 'Writing task failed');
    }

    return result.result || '';
  }

  // 润色文本
  async polish(text: string, style?: string): Promise<string> {
    return this.write(text, 'polish', { style });
  }

  // 扩写文本
  async expand(text: string, direction?: string): Promise<string> {
    return this.write(text, 'expand', { expansionDirection: direction });
  }

  // 续写内容
  async continue(text: string, context?: string): Promise<string> {
    return this.write(text, 'continue', { context });
  }

  // 生成摘要
  async summarize(text: string, length?: number): Promise<string> {
    return this.write(text, 'summarize', { targetLength: length });
  }

  // 生成内容
  async generate(prompt: string, style?: string): Promise<string> {
    return this.write(prompt, 'generate', { style });
  }

  // 添加任务到队列
  addTask(task: Omit<WritingTask, 'id' | 'createdAt'>): string {
    const fullTask: WritingTask = {
      ...task,
      id: uuidv4(),
      createdAt: new Date(),
    };

    this.taskQueue.push(fullTask);

    // 按优先级排序
    this.taskQueue.sort((a, b) => b.priority - a.priority);

    // 启动处理（如果未在处理中）
    if (!this.isProcessing) {
      this.processQueue();
    }

    return fullTask.id;
  }

  // 处理任务队列
  private async processQueue(): Promise<void> {
    if (this.isProcessing || this.taskQueue.length === 0) {
      return;
    }

    this.isProcessing = true;

    while (this.taskQueue.length > 0) {
      const task = this.taskQueue.shift();
      if (!task) break;

      try {
        await this.processTask(task);
      } catch (error) {
        console.error(`Failed to process task ${task.id}:`, error);
      }
    }

    this.isProcessing = false;
  }

  // 获取上下文
  private async getContext(task: WritingTask): Promise<string | null> {
    if (!this.config.autoContext || !task.context) {
      return null;
    }

    const contextParts: string[] = [];

    // 项目信息
    if (task.context.projectOverview) {
      contextParts.push(`项目信息: ${task.context.projectOverview}`);
    }

    // 章节摘要
    if (task.context.chapterSummary) {
      contextParts.push(`当前章节: ${task.context.chapterSummary}`);
    }

    // 选中文本
    if (task.context.selectedText) {
      contextParts.push(`选中文本: ${task.context.selectedText}`);
    }

    // 周围文本
    if (task.context.surroundingText) {
      contextParts.push(`上下文: ${task.context.surroundingText}`);
    }

    // 用户偏好
    if (task.context.userPreferences) {
      contextParts.push(`用户偏好: ${JSON.stringify(task.context.userPreferences)}`);
    }

    // 写作历史
    if (task.context.writingHistory && task.context.writingHistory.length > 0) {
      const recentHistory = task.context.writingHistory.slice(-3);
      contextParts.push(`最近操作: ${recentHistory.map(h => `${h.action}: ${h.input.substring(0, 50)}...`).join(', ')}`);
    }

    return contextParts.join('\n') || null;
  }

  // 构建消息
  private async buildMessages(task: WritingTask, context: string | null): Promise<any[]> {
    const promptManager = getPromptTemplateManager();

    // 获取系统提示词
    let systemPrompt = promptManager.formatPrompt('intellimark-assistant', {
      context: context || '无特定上下文',
      document_info: task.context ? `项目: ${task.context.projectId || '未指定'}, 章节: ${task.context.chapterId || '未指定'}` : '无文档信息'
    }) || '你是一个专业的IntelliMark AI写作助手。';

    // 根据任务类型调整系统提示词
    switch (task.type) {
      case 'polish':
        systemPrompt += '\n\n当前任务: 文本润色优化，保持原意，提升表达质量。';
        break;
      case 'expand':
        systemPrompt += '\n\n当前任务: 文本扩写，增加细节和内容，保持逻辑连贯。';
        break;
      case 'continue':
        systemPrompt += '\n\n当前任务: 内容续写，保持风格一致，推进内容发展。';
        break;
      case 'summarize':
        systemPrompt += '\n\n当前任务: 生成摘要，突出核心观点和关键信息。';
        break;
      case 'generate':
        systemPrompt += '\n\n当前任务: 创意写作，根据提示生成高质量内容。';
        break;
    }

    // 构建用户提示词
    let userPrompt = '';

    switch (task.type) {
      case 'polish':
        userPrompt = `请润色以下Markdown文本：\n\n${task.input}`;
        break;
      case 'expand':
        userPrompt = `请扩写以下Markdown文本：\n\n${task.input}\n\n扩写方向: ${task.options?.expansionDirection || '增加更多细节和描述'}`;
        break;
      case 'continue':
        userPrompt = `请续写以下内容：\n\n${task.input}\n\n上下文: ${task.options?.context || '无特定上下文'}`;
        break;
      case 'summarize':
        userPrompt = `请为以下文本生成摘要：\n\n${task.input}\n\n目标长度: ${task.options?.targetLength || '200字左右'}`;
        break;
      case 'generate':
        userPrompt = `请根据以下提示生成Markdown内容：\n\n${task.input}\n\n风格: ${task.options?.style || this.config.defaultStyle}`;
        break;
      default:
        userPrompt = task.input;
    }

    return [
      new SystemMessage(systemPrompt),
      new HumanMessage(userPrompt)
    ];
  }

  // 执行任务
  private async executeTask(messages: any[], task: WritingTask): Promise<{ content: string }> {
    const providerManager = getEnhancedAIProviderManager();

    const response = await providerManager.generateEnhancedResponse(
      messages,
      undefined, // 使用默认提供商
      {
        temperature: this.getTemperatureForTask(task.type),
        maxTokens: this.getMaxTokensForTask(task.type),
      }
    );

    return {
      content: response.content,
    };
  }

  // 从任务中学习
  private async learnFromTask(task: WritingTask, response: { content: string }): Promise<void> {
    if (!this.config.learningEnabled) return;

    // 存储学习样本
    const learningKey = `${task.type}_${this.config.defaultStyle}`;
    const samples = this.memory.get(learningKey) || [];

    samples.push({
      input: task.input,
      output: response.content,
      timestamp: new Date(),
      context: task.context,
    });

    // 保持样本数量在合理范围内
    if (samples.length > 100) {
      samples.shift();
    }

    this.memory.set(learningKey, samples);
  }

  // 存储记忆
  private async storeMemory(task: WritingTask, response: { content: string }): Promise<void> {
    if (!this.config.memoryEnabled) return;

    // 存储写作历史
    const memoryKey = `writing_history_${task.context?.projectId || 'default'}`;
    const history = this.memory.get(memoryKey) || [];

    history.push({
      taskId: task.id,
      type: task.type,
      input: task.input,
      output: response.content,
      timestamp: new Date(),
      context: task.context,
    });

    // 保持历史记录在合理范围内
    if (history.length > 1000) {
      this.memory.splice(0, history.length - 1000);
    }

    this.memory.set(memoryKey, history);
  }

  // 获取任务类型的温度设置
  private getTemperatureForTask(taskType: WritingTaskType): number {
    switch (taskType) {
      case 'generate':
        return 0.8; // 创意性任务需要较高温度
      case 'polish':
        return 0.3; // 润色需要较低温度保持一致性
      case 'expand':
      case 'continue':
        return 0.6; // 扩写和续写中等温度
      case 'summarize':
        return 0.4; // 摘要需要较低温度确保准确性
      default:
        return 0.7;
    }
  }

  // 获取任务类型的最大token设置
  private getMaxTokensForTask(taskType: WritingTaskType): number {
    switch (taskType) {
      case 'summarize':
        return 500; // 摘要较短
      case 'polish':
        return 1000; // 润色中等长度
      case 'expand':
      case 'continue':
        return 2000; // 扩写和续写较长
      case 'generate':
        return 3000; // 生成任务最长
      default:
        return 1500;
    }
  }

  // 获取Agent统计信息
  public getStats(): {
    queueLength: number;
    isProcessing: boolean;
    memorySize: number;
    specialties: WritingTaskType[];
    config: WritingAgentConfig;
  } {
    return {
      queueLength: this.taskQueue.length,
      isProcessing: this.isProcessing,
      memorySize: this.memory.size,
      specialties: this.config.specialties,
      config: this.config,
    };
  }

  // 清空队列
  public clearQueue(): void {
    this.taskQueue = [];
  }

  // 清空记忆
  public clearMemory(): void {
    this.memory.clear();
  }

  // 更新配置
  public updateConfig(newConfig: Partial<WritingAgentConfig>): void {
    this.config = { ...this.config, ...newConfig };
  }

  // 获取写作历史
  public getWritingHistory(projectId?: string): any[] {
    const memoryKey = `writing_history_${projectId || 'default'}`;
    return this.memory.get(memoryKey) || [];
  }

  // 获取学习样本
  public getLearningSamples(taskType?: WritingTaskType): any[] {
    if (taskType) {
      const learningKey = `${taskType}_${this.config.defaultStyle}`;
      return this.memory.get(learningKey) || [];
    }

    const allSamples: any[] = [];
    this.memory.forEach((value, key) => {
      if (key.startsWith('learning_')) {
        allSamples.push(...value);
      }
    });
    return allSamples;
  }
}

// 导出便捷函数
export const createWritingAgent = (config?: Partial<WritingAgentConfig>): WritingAgent => {
  return new WritingAgent(config);
};

// 默认实例
export const defaultWritingAgent = new WritingAgent();